package com.most.auth.service.impl;

import com.most.api.UserVO;
import com.most.auth.dto.User;
import com.most.auth.mapper.UserMapper;
import com.most.redis.RedisUtil;
import com.most.auth.service.LoginService;
import com.most.util.JwtUtils;
import com.most.util.SecurityConstants;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;
    public String getPassword(String password,String salt) {
        Md5Hash md5Hash = new Md5Hash(password, salt, 1024);
        return md5Hash.toHex();
    }
    @Override
    public String login(String username, String password) {
        User user = userMapper.findByUserName(username);
        if (null==user){
            return "用户不存在！";
        }
        password = getPassword(password, user.getSalt());
        if (!password.equals(user.getPassword())){
            return "密码错误！";
        }
        long currentTimeMillis = System.currentTimeMillis();
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, String.valueOf(currentTimeMillis));
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, user.getId());
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, user.getUsername());
        String token = JwtUtils.createToken(claimsMap);
        redisUtil.set(username, currentTimeMillis, 60 * 30);
        return token;
    }

}
